const util = require('../../utils/util');
const StatisticsService = require('../../service/admin/teacher-statistics.service');
const WebSocketManager = require('../../service/common/websocket-util');
const wss = WebSocketManager.getInstance();
async function createStatistics(ctx) {
	const { year, month, teacherId, teacherCommonType, totalTeaching, totalClassCount, totalHours, remark, deptScope } = ctx.request.body;

	if (!year || !month || !teacherId || !teacherCommonType) {
		return util.fail(ctx, '年份、月份、教师 ID 或类型不能为空');
	}

	try {
		const result = await StatisticsService.createStatistics({
			year,
			month,
			teacherId,
			teacherCommonType,
			totalTeaching,
			totalClassCount,
			totalHours,
			remark,
			deptScope,
			createId: ctx.state.user.id, // 从 JWT 获取
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `新增统计失败: ${error.message}`);
	}
}

async function deleteStatistics(ctx) {
	const { ids } = ctx.request.body;

	if (!Array.isArray(ids) || !ids.length) {
		return util.fail(ctx, 'ID 列表无效');
	}

	try {
		const result = await StatisticsService.deleteStatistics(ctx, ids);
		util.success(ctx, { ids });
	} catch (error) {
		util.fail(ctx, `删除统计失败: ${error.message}`);
	}
}

async function updateStatistics(ctx) {
	const { id, year, month, teacherId, teacherCommonType, totalTeaching, totalClassCount, totalHours, remark, deptScope } = ctx.request.body;

	if (!id) {
		return util.fail(ctx, 'ID 不能为空');
	}

	try {
		const result = await StatisticsService.updateStatistics(ctx, {
			id,
			year,
			month,
			teacherId,
			teacherCommonType,
			totalTeaching,
			totalClassCount,
			totalHours,
			remark,
			deptScope,
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `修改统计失败: ${error.message}`);
	}
}

async function listStatistics(ctx) {
	wss.broadcast('全体公告：请注意系统维护!');
	const { userId } = util.decodeToken(ctx);
	const { page = 1, limit = 10, year, month } = ctx.query;

	try {
		const result = await StatisticsService.listStatistics(userId, {
			page: +page,
			limit: +limit,
			year,
			month,
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `查询统计失败: ${error.message}`);
	}
}

module.exports = { createStatistics, deleteStatistics, updateStatistics, listStatistics };
